package com.tecniplast.selene.controller;



import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dom4j.DocumentException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.tecniplast.selene.common.util.CheckUtil;
import com.tecniplast.selene.common.util.MessageUtils;
import com.tecniplast.selene.factory.CacheFactory;
import com.tecniplast.selene.service.AutoReplyService;

@Controller
public class WeixinController {
	
	@Autowired
    private AutoReplyService autoReplyService;
	
	/**
	 * 微信接口主入口
	 * 信息验证
	 * @param model
	 */
	@RequestMapping(value = "/mainEntry", method = RequestMethod.GET)
	@ResponseBody
    public void mainCheck(@RequestBody byte[] bytes,HttpServletRequest request,HttpServletResponse response) {
		String signature = request.getParameter("signature");
		String timestamp = request.getParameter("timestamp");
		String nonce = request.getParameter("nonce");
		String echostr = request.getParameter("echostr");
		PrintWriter out;
		try {
			out = response.getWriter();
			if(CheckUtil.checkSignature(signature, timestamp, nonce)){
				out.print(echostr);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
    }
	
	/**
	 * 微信接口主入口
	 * @param model
	 */
	@RequestMapping(value = "/mainEntry", method = RequestMethod.POST)
	@ResponseBody
    public String mainEntry(HttpServletRequest request,HttpServletResponse response) {
		Map<String, String> map = null;
		String message = "";
		try {
			map = MessageUtils.xmlToMap(request);
			String msgType = map.get("MsgType");
			//text 类型
			if(msgType.equals(CacheFactory.getInstance().getMapByKey("syscodeList", "1"))){
				message = autoReplyService.msgDeal(map);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		return message;
    }
}
